import { join } from 'path'
import Datastore from 'nedb-promises'

let basePath = __dirname

const dbFactory = (fileName: string) => Datastore.create({
  filename: join(basePath, `/data/${fileName}.db`),
  timestampData: true,
  autoload: true
})

function setBasePath (bp: string) {
  basePath = bp
}

function getBasePath () {
  return basePath
}

const data = {
  setBasePath,
  getBasePath
}

let novelsIns: Datastore | null = null

let sourcesIns: Datastore | null = null

export default {
  sources: () => { 
    if (sourcesIns === null) {
      sourcesIns = dbFactory('sources')
    }
    return sourcesIns
  },
  novels: () => {
    if (novelsIns === null) {
      novelsIns = dbFactory('novels')
    }
    return novelsIns
  },
  setBasePath,
  getBasePath
}
